package impl

import (
	"context"

	"gitee.com/hexug/devcloud/mcenter/apps/permission"
	"gitee.com/hexug/devcloud/mcenter/apps/policy"
	"gitee.com/hexug/devcloud/mcenter/common/validate"
)

func (i *implServer) CheckPermission(ctx context.Context,
	in *permission.CheckPermissionRequest) (
	*permission.CheckPermissionResponse,
	error) {
	if err := validate.V().Struct(in); err != nil {
		return nil, err
	}
	qpr := policy.NewQueryPolicyRequestValidata()
	qpr.UserId = in.UserId
	qpr.Namespace = in.Namespace
	qpr.WithRole = true
	ps, err := i.p.QueryPolicy(ctx, qpr)
	if err != nil {
		return nil, err
	}
	cpmr := permission.NewCheckPermissionResponse()
	for _, poli := range ps.Items {
		if ok := poli.Role.HasFeatrue(
			in.ServiceId,
			in.HttpMethod,
			in.HttpPath); ok {
			cpmr.HasPermisson = true
			cpmr.Policy = poli
		}
	}
	return cpmr, nil
}
